package com.gupao.rpc.protocol.codec;

import com.gupao.rpc.protocol.constants.RpcConstant;
import com.gupao.rpc.protocol.protocol.Header;
import com.gupao.rpc.protocol.protocol.RequestHolder;
import com.gupao.rpc.protocol.protocol.RpcProtocol;
import com.gupao.rpc.protocol.serializer.IRpcSerializer;
import com.gupao.rpc.protocol.serializer.RpcSerializerManager;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;

/**
 * 编码器
 *
 * @author SuperWein
 */
@Slf4j
public class RpcEncoder extends MessageToByteEncoder<RpcProtocol<Object>> {

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, RpcProtocol rpcProtocol, ByteBuf out) throws Exception {
        log.info("============begin RpcEncoder=========");
        Header header = rpcProtocol.getHeader();
        out.writeShort(RpcConstant.MAGIC);
        out.writeByte(header.getReqType());
        out.writeByte(header.getSerialType());
        out.writeLong(header.getRequestId());
        Object body = rpcProtocol.getBody();
        IRpcSerializer serializer = RpcSerializerManager.getSerializer(header.getSerialType());
        byte[] bodyBytes = serializer.serialize(body);
        out.writeInt(bodyBytes.length);
        out.writeBytes(bodyBytes);
    }

}
